<template>
	<fc-designer ref="designer" :config="_config" :handle="handle" :locale="locale" @drag="handleDrag" :option="option">
		<template #handle>
			<slot name="handle"></slot>
		</template>
	</fc-designer>
</template>

<script>
	import {
		domToPng
	} from 'modern-screenshot'

	import {
		snapdom
	} from '@zumer/snapdom';

	// https://view.form-create.com/append-rule
	// 扩展表单配置

	import ActRules from './activity/rule.js'
	import ActComponents from './activity/index.js'
	import ActStyles from "./activity/style.js"

	import Rules from './components/rule/index.js'
	import Components from './components/index.js'
	import Styles from "./components/style/index.js"

	import ZhCN from "./locale/zh-cn.js";

	import FcDesigner from '@form-create/designer'

	import Text from './components/rule/text.js'
	import Input from './components/rule/input.js'

	FcDesigner.component('Text', Text);
	FcDesigner.component('Input', Input);

	export default {
		components: {

		},
		props: {
			config: {
				type: [Object],
				default: ''
			},
			handle: {
				type: [Array],
				default: ''
			}
		},
		beforeUnmount() {
			try {
				//document.querySelector('._fc-m-drag.pc').removeEventListener("scroll")
			} catch (e) {

			}
		},
		mounted() {
			/*
						const trigger = document.querySelector('._fc-m-drag.pc')
						trigger.addEventListener('scroll', () => {
							const scrollY = trigger.scrollTop; // 获取滚动位置
							document.querySelectorAll("._fc-draggable-item:has(.ta-fab)").forEach(content => {
								content.style.transform = `translateY(${scrollY}px)`;
							})
						});
			*/
			window.onbeforeunload = null;

			// 添加活动组件
			this.$refs.designer.addMenu({
				name: 'activity',
				title: '活动组件',
				list: []
			});
			this.$refs.designer.menuList.unshift(this.$refs.designer.menuList.pop());

			// 添加商城组件
			this.$refs.designer.addMenu({
				name: 'shop',
				title: '商城组件',
				list: []
			});
			const lastElement = this.$refs.designer.menuList.pop();
			this.$refs.designer.menuList.unshift(lastElement);

			// 活动组件
			Object.keys(ActRules).forEach(key => {
				this.$refs.designer.addComponent(ActRules[key])
			})
			Object.keys(ActComponents).forEach(key => {
				FcDesigner.component(ActComponents[key].name, ActComponents[key]);
			})
			Object.keys(ActStyles).forEach(key => {
				FcDesigner.component(ActStyles[key].name, ActStyles[key]);
			})

			// 非活动
			Object.keys(Rules).forEach(key => {
				this.$refs.designer.addComponent(Rules[key])
			})
			Object.keys(Components).forEach(key => {
				FcDesigner.component(Components[key].name, Components[key]);
			})

			Object.keys(Styles).forEach(key => {
				FcDesigner.component(Styles[key].name, Styles[key]);
			})

		},
		computed: {
			_config() {
				return {
					...{
						appendConfigData: ['formCreateMark'],
						formRule: {
							prepend: true,
							// append: true, // 添加到底部
							rule() {
								return [{
									type: 'input',
									//配置名称, 修改 options.mark
									field: 'formCreateMark',
									title: '页面备注'
								}]
							}
						},
						formOptions: {
							form: {
								labelPosition: "top"
							}
						},
						hiddenItem: [''],
						hiddenMenu: [''],
						fieldReadonly: false,
						showBaseForm: true, // 字段名称之类的
						showEventForm: false,
						showJsonPreview: true,
						showStyleForm: false, // 样式
						showConfig: true,
						showLanguage: false,
						showSaveBtn: false,
						showControl: false
					},
					...this.config
				}
			}
		},
		data() {
			// https://view.form-create.com/hidden-item
			return {
				locale: ZhCN,
				option: {

				}
			};
		},
		methods: {
			trimTransparentBorder(image) {
				const canvas = document.createElement('canvas');
				const ctx = canvas.getContext('2d');

				canvas.width = image.width;
				canvas.height = image.height;
				ctx.drawImage(image, 0, 0);

				const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
				const data = imageData.data;
				const w = image.width; // 使用原始宽度计算像素位置

				let top = 0,
					bottom = image.height,
					left = 0,
					right = w;

				// 扫描顶部
				scanTop: for (; top < bottom; top++) {
					for (let x = 0; x < w; x++) {
						if (data[(top * w + x) * 4 + 3] !== 0) {
							break scanTop;
						}
					}
				}

				// 扫描底部
				scanBottom: for (; bottom > top; bottom--) {
					for (let x = 0; x < w; x++) {
						if (data[((bottom - 1) * w + x) * 4 + 3] !== 0) {
							break scanBottom;
						}
					}
				}

				// 扫描左侧
				scanLeft: for (; left < right; left++) {
					for (let y = top; y < bottom; y++) {
						if (data[(y * w + left) * 4 + 3] !== 0) {
							break scanLeft;
						}
					}
				}

				// 扫描右侧（关键修正）
				scanRight: for (; right > left; right--) {
					for (let y = top; y < bottom; y++) {
						if (data[(y * w + (right - 1)) * 4 + 3] !== 0) {
							break scanRight;
						}
					}
				}

				const trimmedCanvas = document.createElement('canvas');
				const trimmedCtx = trimmedCanvas.getContext('2d');
				trimmedCanvas.width = right - left;
				trimmedCanvas.height = bottom - top;

				trimmedCtx.drawImage(
					canvas,
					left, top,
					right - left, bottom - top,
					0, 0,
					right - left, bottom - top
				);

				return trimmedCanvas.toDataURL();
			},

			async domToPng(cb) {
				this.$refs.designer.clearActiveRule()

				this.$nextTick(async () => {
					const el = document.querySelector('._fc-m-drag.pc');
					const result = await snapdom(el, {
						scale: 1
					});
					const img = await result.toPng();
					const trimmedData = this.trimTransparentBorder(img);
					cb && cb(trimmedData);
				});
				return;
				//				console.error(img.src)


				domToPng(document.querySelector('._fc-m-drag.pc')).then(dataUrl => {
					cb && cb(dataUrl);
					return;
					console.error(dataUrl)
					const link = document.createElement('a')
					link.download = 'screenshot.png'
					link.href = dataUrl
					link.click()
				})
			},
			preStep() {
				const element = document.querySelector('.fc-icon.icon-pre-step');
				if (element) element.click();
			},
			addMenu(data) {
				return this.$refs.designer.addMenu(data)
			},
			getOption() {
				return this.$refs.designer.getOption()
			},
			getRule() {
				return this.$refs.designer.getRule()
			},
			setRule(data) {
				return this.$refs.designer.setRule(data)
			},
			setOption(data) {
				return this.$refs.designer.setOption(data)
			},
			getJson() {
				return this.$refs.designer.getJson();
			},
			handleDrag(e) {
				/*
					TaFab 浮动的只能有一个
				*/
				this.$nextTick(() => {
					setTimeout(() => {
						var count = this.$refs.designer.getRule().filter(item => item.type === 'TaFab')
							.length;
						if (count == 2) {
							// this.preStep();
						}
					}, 200)
				})
				return false;
			}
		}
	}
</script>

<style scoped>
	/* https://www.zxlee.cn/github/uni-z-paging/phone.png */

	/* 右边宽度*/
	:deep(.el-aside._fc-r) {
		width: 550px !important;
		border-right: 1px solid #ddd;
	}

	:deep(.el-main._fc-m-con) {
		background-image: url('https://blkq-static.oss-cn-shenzhen.aliyuncs.com/static/images/comm/iphone6s.png');
		background-repeat: no-repeat;
		background-position: center;
		background-size: 450px 768px;
		justify-content: center;
		display: flex;
		align-items: center;
		padding: 0 !important;
	}

	:deep(._fc-m-drag.pc) {
		width: 579px;
		height: 671px;

		padding: 0px;
		overflow: auto;
		padding-right: 100px;
		padding-left: 100px;
		background-color: transparent;
		scrollbar-width: none;
	}

	:deep(._fc-m-drag.pc > .el-form) {
		border: 2px solid #ddd;
		height: auto;
		min-height: 100%;
	}

	:deep(._fc-m-input) {
		padding: 3px;
	}

	/* 取消页面 滚动条 */
	:deep(._fd-draggable-drag) {
		scrollbar-width: none;
		padding: 0px 0px 100px !important;
		overflow: visible !important;
	}

	/*
		干掉选择设备
	*/
	:deep(._fc-m-tools-l .devices) {
		display: none;
	}

	:deep(._fc-m-tools-l .line) {
		display: none;
	}

	:deep(.icon-title) {
		width: 21px;
		height: 21px;
		background-image: url('https://fe-1304214004.cos.ap-beijing.myqcloud.com/images/ssp/ab181a88-ffc3-41e0-885a-5ab5b931540d.png');
		background-size: 21px 21px;
		background-repeat: no-repeat;
	}

	:deep(._fd-drag-tool) {
		padding: 0px;
		outline: 1px dashed transparent;
		overflow: visible;
	}

	:deep(._fd-drag-tool.active) {
		outline: 1px dashed var(--fc-tool-border-color);
	}

	:deep(._fd-drag-tool:hover) {
		outline: 1px dashed var(--fc-tool-border-color);
	}

	:deep(._fd-drag-tool.active>div>._fd-drag-btn) {
		/*display: none;*/
	}

	:deep(._fd-drag-tool.active:hover>div>._fd-drag-btn) {
		display: flex;
	}


	:deep(._fc-draggable-item:has(.ta-fab)) {
		position: absolute;
		top: 0px;
		right: 0px;
		width: 22px;
		z-index: 2000;
	}

	:deep(._fc-draggable-item:has(.ta-fab) ._fd-drag-tool.active) {
		display: flex;
		z-index: 2000;
	}

	:deep(._fd-drag-box>div[data-draggable]:has(.active)) {
		margin-top: 1px;
		margin-bottom: 1px;
	}

	:deep(._fd-drag-box>div[data-draggable]) {
		margin-left: 1px;
		margin-right: 1px;
		margin-top: 1px;
		margin-bottom: 1px;
	}

	/*
	隐藏预览按钮
	*/
	:deep(button:has(.icon-preview)) {
		display: none;
	}

	:deep(.line) {
		display: none !important;
	}

	:deep(div._fd-input-btn) {
		display: none !important;
	}

	/*表单 padding*/
	:deep(._fc-m-drag.pc .actqa .el-form-item) {
		padding: 5px 15px 5px;
	}

	:deep(.el-form-item) {
		margin-bottom: 0px !important;
	}

	/**/
	:deep(._fd-drag-mask) {
		right: -100px !important;
		/*background-color: red;*/
		opacity: 0.1;
	}

	:deep(._fd-drag-r) {
		right: -45px !important;
	}

	/*
	:deep(.el-row.fc-form-row) {
		height: auto;
		transform: translateZ(0);
	}
*/

	/*
	悬浮组件处理
	*/
	:deep(._fc-draggable-item:has(.ta-fab) ._fd-drag-tool) {
		outline: 0px dashed var(--fc-tool-border-color);
	}

	:deep(.el-text) {
		white-space: pre-line;
		line-height: normal !important;
		padding: 15px 0px;
		color: rgb(170, 170, 170) !important;
	}

	/*
		中间界面 固定宽度
	*/
	:deep(.el-container.is-vertical._fc-m) {
		/*width: 600px !important;
		flex: initial !important;*/
	}
</style>
